#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<string.h>
using namespace std;

int main()
{
  char buf[1024];
  int id1 = fork();    
  if (id1 == 0)    
  {    
    int id2 = fork();    
    
    if(id2 == 0)    
    {    
      int fd2;
      //cout << "子进程son1读管道FIFO" << endl;
      if(access("FIFO",F_OK))                                                          mkfifo("FIFO",0644);

      fd2 = open("FIFO",O_RDONLY);    
      
      while(1)
      {
        read(fd2, buf, sizeof(buf));    
        cout << "Client->Server:" << buf << endl;
        if(strncmp(buf,"end",3) == 0)
        {
          cout << "Server end read!" << endl;
          break;
        }
      close(fd2);
      } 
    }    
    else     
    {    
      //cout << "子进程son2写管道FIFO1" << endl;    
      int fd1;    
      fd1 = open("FIFO1",O_WRONLY);    
      while(1)
      {
        int cnt = read(0, buf, sizeof(buf));    
        write(fd1, buf, cnt); 
      }

			close(fd1);
    }
  }
  else 
  {
    wait(NULL);
    wait(NULL);
  }

  return 0;
}
